package com.k.liuzh.extraffic.Database;

import android.content.Context;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.QueryBuilder;

import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

public class EnvDao {

    private Context context;

    private Dao<EnvironmentBean,Integer> dao;

    public EnvDao (Context context){
        this.context = context;
        try {
            dao = DatabaseHelper.getInstance(context).getDao(EnvironmentBean.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void add(EnvironmentBean data){
        try {
            dao.create(data);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public List<EnvironmentBean> query(){
        List<EnvironmentBean> list = null;
        try {
            list = dao.queryForAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    public int queryMaxId(){
        int id = 0;
        QueryBuilder queryBuilder = dao.queryBuilder().orderBy("id",true).limit((long)1);
        try {
            List<EnvironmentBean> list= queryBuilder.query();
            id = list.get(0).getId();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return id;
    }

    public Collection<Integer> createIds(){
        Collection<Integer> ids = null;

        for(int i = 0; i < query().size();i++){
            if (query().get(i).getId() <= queryMaxId()-20){
                ids.add(query().get(i).getId());
            }
        }
        return ids;
    }

    public void del(Collection<Integer> ids){
        try {
            dao.deleteIds(createIds());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
